package com.yuxin.tongyi.lsll.sub;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.yuxin.tongyi.lsll.R;
import com.yuxin.tongyi.lsll.common.Constants;
import com.yuxin.tongyi.lsll.common.TongyiTeaApplication;
import com.yuxin.tongyi.lsll.pojo.ClassObj;
import com.yuxin.tongyi.lsll.pojo.LoginInfo;
import com.yuxin.tongyi.lsll.select.SelectClassActivity;
import com.yuxin.tongyi.lsll.thread.GetClassFirstThread;
import com.yuxin.tongyi.lsll.util.HttpRequestUtil;
import com.yuxin.tongyi.lsll.util.PubUtil;


public class NotificationActivity extends BaseActivity {
	
	private LoginInfo loginInfo;
	private Handler myHandler;
	private String classId; // 班级id
	private String className; //班级名称
	private Button sendButton; //发送信息按钮
	private Button rewriteButton; //重写按钮
	private EditText messageText; //信息编辑框
	private TextView limitWords;  //可以发送信息的总字数
	private TextView currentWords; //已经输入信息的字数
	private TextView tvClass;    //班级
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sub_notification);
		
		initialParam();
		setOnClickToButton();
		
		//获取用户名及密码对象
		getUserInfo();
		
		PubUtil.showProgressDialog(NotificationActivity.this, Constants.MSG_LOADING, Constants.MSG_WAIT);
		//启动获取班级列表的线程
		new Thread(new GetClassFirstThread(this, myHandler)).start();
	}
	
	/**
	 * 获取用户名及密码对象
	 */
	private void getUserInfo(){
		try {
			loginInfo = (LoginInfo) TongyiTeaApplication.getMap().get(Constants.GLOBAL_LOGININFO);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 读取未写完的短信及班级索引
	 */
	@Override
	protected void onResume() {
		super.onResume();
		String saveContent = PubUtil.getConfigValue(NotificationActivity.this, Constants.CFG_MESSAGE_CONTENT, "");
		classId = PubUtil.getConfigValue(NotificationActivity.this, Constants.CFG_MESSAGE_CLASS_ID, "0");
		className = PubUtil.getConfigValue(NotificationActivity.this, Constants.CFG_MESSAGE_CLASS_NAME, "");
		messageText.setText(saveContent);
	}
	
	/**
	 * 中断activity时保存未写完的短信及班级索引
	 */
	@Override
	protected void onPause() {
		super.onPause();
		//获取编辑的短信内容
		String saveContent = messageText.getText().toString();
		
		PubUtil.setConfigValue(NotificationActivity.this, Constants.CFG_MESSAGE_CONTENT, saveContent);
		PubUtil.setConfigValue(NotificationActivity.this, Constants.CFG_MESSAGE_CLASS_ID, classId);
		PubUtil.setConfigValue(NotificationActivity.this, Constants.CFG_MESSAGE_CLASS_NAME, className);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case Constants.REQUEST_CODE_ClASS:
			if (resultCode == Activity.RESULT_OK) {
				Bundle b = data.getExtras();
				if(b != null){
					String SelectClassId = b.getString(Constants.SELECT_CLASS_ID);
					className = b.getString(Constants.SELECT_CLASS_NAME);
					if(!SelectClassId.equals(classId)){
						classId = SelectClassId;
						tvClass.setText(className);
					}
				}
			}
			break;
		}
	}

	/**
	 * 参数初始化
	 */
	
	private void initialParam(){
		myHandler = new MyHandler();
		sendButton = (Button)findViewById(R.id.noticeSendButton);
		rewriteButton = (Button)findViewById(R.id.rewriteButton);
		messageText = (EditText)findViewById(R.id.sub_messageContent);
		limitWords = (TextView)findViewById(R.id.limitWords);
		currentWords = (TextView)findViewById(R.id.currentWords);
		
		tvClass = (TextView) findViewById(R.id.sub_noticeSend_tvClassName);
		
	}
	
	/**
	 * 绑定监听器
	 */
	private void setOnClickToButton(){
		//绑定重写按钮监听器
		rewriteButton.setOnClickListener(new RewriteListener());
		//绑定发送按钮监听器
		sendButton.setOnClickListener(new SendMessageListener());
		//绑定文本编辑框监听器
		messageText.addTextChangedListener(new MyTextWatch());
		//绑定班级监听器
		tvClass.setOnClickListener(new onClassClick());
	} 
	
	class onClassClick implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent();
			intent.setClass(NotificationActivity.this, SelectClassActivity.class);
			startActivityForResult(intent, Constants.REQUEST_CODE_ClASS);
		}
	}
	
	/**
	 * 发送按钮监听器
	 */
	class SendMessageListener implements OnClickListener{
		@Override
		public void onClick(View arg0) {
			HttpRequestUtil request = new HttpRequestUtil();
			String msgContent = messageText.getText().toString().trim();
			if(msgContent != null && !"".equals(msgContent)){
				PubUtil.showProgressDialog(NotificationActivity.this, Constants.MSG_SENDING, Constants.MSG_WAIT);
				new Thread(new SendMsgThread(request,msgContent)).start();
			}else{
				PubUtil.showToast(NotificationActivity.this, "请填写内容");
			}
		}
	}
	
	/**
	 * 重写按钮监听器
	 */
	class RewriteListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			messageText.setText("");
		}
	}
	
	/**
	 * 信息输入框监听器
	 */
	class MyTextWatch implements TextWatcher{

		@Override
		public void afterTextChanged(Editable ed) {
			if(ed.length()>0){
				//当输入信息时，显示限制字符数和已输入的字符数
				limitWords.setVisibility(0);
				currentWords.setVisibility(0);
				//设置当前已输入文字的个数
				currentWords.setText(ed.length() + "");
			}
			//没有文字时，隐藏显示字数的文本框
			if(ed.length() == 0){
				limitWords.setVisibility(4);
				currentWords.setVisibility(4);
			}
			//当输入达到最大限度时提示用户
			if(ed.length() == 400){
				PubUtil.showToast(NotificationActivity.this, "你输入的已到最大字数");
			}
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			
		}

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			
		}
	}
	
	/**
	 * 处理message
	 */
	class MyHandler extends Handler{
	
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle bundle = msg.getData();
			//若服务器无响应则加载之前的数据
			switch (msg.what) {
			case Constants.TH_CLASS_ON:
				ClassObj classObj = (ClassObj) bundle.getSerializable(Constants.STREAM_CLASS_FIRST);
				setClassData(classObj);
				PubUtil.closeProgressDialog();
				break;
			//读取CLASS失败，加载缓存
			case Constants.TH_CLASS_OFF:
				ClassObj classObj1 = (ClassObj) bundle.getSerializable(Constants.STREAM_CLASS_FIRST);
				setClassData(classObj1);
				PubUtil.closeProgressDialog();
				PubUtil.showToastLong(NotificationActivity.this, Constants.MSG_READCACHE);	
				
				break;
			case Constants.NOTICE_SEND_SUCCESS:
				PubUtil.closeProgressDialog();
				//发送成功后，设置文本编辑框为空
				messageText.setText("");
				PubUtil.showDialog(NotificationActivity.this, "提示","发送成功",null,false);
				break;
			case Constants.NOTICE_SEND_FAIL:
				PubUtil.closeProgressDialog();
				PubUtil.showDialog(NotificationActivity.this, "提示","发送失败，请重新发送",null,false);
			}
		}
	}
	
	private void setClassData(ClassObj info) {
		classId = info.getClassId();
		className = info.getClassName();
		
		tvClass.setText(className);
	}
	
	/**
	 * 发送短信息线程
	 */
	class SendMsgThread implements Runnable{
		private HttpRequestUtil request;
		private String msgContent;
		public SendMsgThread(HttpRequestUtil request,String msgContent){
			this.request = request;
			this.msgContent = msgContent;
		}
		@Override
		public void run() {
			boolean flag = request.noticeSendRequest(loginInfo.getLoginName(), loginInfo.getPassword(), msgContent,classId);
			String status = request.getStatus();
			//创建一个Message
			Message message = new Message();
			//status为0时发送失败，为1时发送成功
			if(flag && "1".equals(status)){
				message.what = Constants.NOTICE_SEND_SUCCESS;
				myHandler.sendMessage(message);
			}else{
				message.what = Constants.NOTICE_SEND_FAIL;
				myHandler.sendMessage(message);
			}
		}
	}
	
}
